package com.qsmx.store.app.main.suit;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatRadioButton;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.qsmx.store.app.R;
import com.qsmx.store.app.R2;
import com.qsmx.store.app.entity.suit.SuitDetailEntity;
import com.qsmx.store.app.event.CardReadEvent;
import com.qsmx.store.app.fustion.FustionManager;
import com.qsmx.store.app.fustion.FustionTag;
import com.qsmx.store.app.http.HttpHelper;
import com.qsmx.store.app.http.HttpUrl;
import com.qsmx.store.app.main.mem.entity.MemInfoEntity;
import com.qsmx.store.app.main.suit.adapter.SuitHomeAdapter;
import com.qsmx.store.app.main.suit.entity.AuthorizeRecord;
import com.qsmx.store.app.util.CardReadUtil;
import com.qsmx.store.app.util.CountDownTimerUtil;
import com.qsmx.store.app.util.DisplayUtil;
import com.qsmx.store.app.util.StringUtil;
import com.qsmx.store.app.widget.MyDialog;
import com.qsmx.store.core.delegates.AtmosDelegate;
import com.qsmx.store.core.event.QrScanEvent;
import com.qsmx.store.core.fusion.FusionCode;
import com.qsmx.store.core.fusion.FusionString;
import com.qsmx.store.core.net.callback.IError;
import com.qsmx.store.core.net.callback.IFailure;
import com.qsmx.store.core.net.callback.ISuccess;
import com.qsmx.store.core.util.dimen.DimenUtil;
import com.qsmx.store.core.util.log.AtmosLogger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import butterknife.BindView;

public class SuitChildDelegate extends AtmosDelegate {

    private String mCoinOutType = "";
    private MyDialog mPayStatusDialog = null;
    private Dialog mCoinOutDialog = null;
    private Dialog mPaySuitDetailDialog = null;
    private CountDownTimerUtil timer;
    private SuitDetailEntity mSuitDetailEntity;
    private SuitHomeAdapter mAdapter;
    private int SUIT_NUM;
    private int suitId;
    private static final String TAG = "SuitCoinOut";
    private List<String> mAccountList = new ArrayList<>();
    private ArrayAdapter accountArrayAdapter;
    private List<AuthorizeRecord> mAuthorizeRecordList;
    private MemInfoEntity mSearchMenInfo;
    private String mCurrentBillNo;
    private String mCurrentPrice;
    private String mCurrentSuitName;
    private String mCurrentTotalCoin;
    private AppCompatTextView tvCoinOutNum;
    private AppCompatEditText etIcCardNum;
    private boolean isReadNow = false;
    private char mReadCardTag = 0x04;
    private int machineStatus;

    @BindView(R2.id.rlv_suit)
    RecyclerView rlvSuit = null;

    public static SuitChildDelegate create(int suitNum, int suitTypeId) {

        final Bundle args = new Bundle();
        args.putInt(FustionTag.SUIT_NUM, suitNum);
        args.putInt(FustionTag.SUIT_ID, suitTypeId);
        final SuitChildDelegate delegate = new SuitChildDelegate();
        delegate.setArguments(args);
        return delegate;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Bundle args = getArguments();
        if (args != null) {
            SUIT_NUM = args.getInt(FustionTag.SUIT_NUM);
            suitId = args.getInt(FustionTag.SUIT_ID);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_suit_child;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        mAuthorizeRecordList = new ArrayList<>();
        initRecycler();
        initSuitDetailData();
    }

    private void initSuitDetailData() {
        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", String.valueOf(FustionManager.mLoginData.getUser().getUser().getDept().getId()));
        params.put("id", suitId);

        HttpHelper.RestClientGet(params, HttpUrl.COMBO_DETAIL,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<SuitDetailEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        mSuitDetailEntity = gson.fromJson(response, type);
                        mAdapter.setData(mSuitDetailEntity.getContent());
                        mAdapter.notifyDataSetChanged();

                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });
    }

    private void initRecycler() {

        GridLayoutManager manager;
        if (SUIT_NUM >= 5) {
            manager = new GridLayoutManager(getContext(), 6);
        } else if (SUIT_NUM >= 3 && SUIT_NUM < 5) {
            manager = new GridLayoutManager(getContext(), 4);
        } else {
            manager = new GridLayoutManager(getContext(), 2);
        }
        mAdapter = new SuitHomeAdapter(getContext(), SUIT_NUM);

        rlvSuit.setLayoutManager(manager);
        rlvSuit.setAdapter(mAdapter);

        mAdapter.setonItemClickListener(new SuitHomeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                getParentDelegate().start(new SuitSaleDelegate());
                showSaleSuitDialog(mSuitDetailEntity.getContent().get(position));
                DisplayUtil.showPayCoinDisplay(getContext());
            }
        });
    }


    @SuppressLint("SetTextI18n")
    private void showSaleSuitDialog(final SuitDetailEntity.ContentBean contentBean) {

        mAccountList.add("IC卡");
        mAccountList.add("二维码");

        mPaySuitDetailDialog = new Dialog(getContext(), R.style.dialog);
        mPaySuitDetailDialog.setCancelable(true);
        mPaySuitDetailDialog.show();
        Window window = mPaySuitDetailDialog.getWindow();
        window.setContentView(R.layout.dialog_sale_suit);
        int width = (int) (DimenUtil.getScreenWidth() * 0.8);
        int height = (int) (DimenUtil.getScreenHeight() * 0.9);

        window.setLayout(width, height);

        final AppCompatSpinner spAccount = window.findViewById(R.id.sp_account);
        accountArrayAdapter = new ArrayAdapter(getContext(), R.layout.item_mem_type_select, mAccountList);
        accountArrayAdapter.setDropDownViewResource(R.layout.item_mem_type_drop);
        spAccount.setAdapter(accountArrayAdapter);

        final AppCompatEditText etPhone = window.findViewById(R.id.et_phone);
        AppCompatTextView tvSearch = window.findViewById(R.id.tv_search);
        final AppCompatTextView tvMemNum = window.findViewById(R.id.tv_mem_num);
        final AppCompatTextView tvCardUseTime = window.findViewById(R.id.tv_card_use_time);
        final AppCompatTextView tvMemName = window.findViewById(R.id.tv_mem_name);
        etIcCardNum = window.findViewById(R.id.et_ic_card_num);
        AppCompatTextView tvErrorTips = window.findViewById(R.id.tv_error_tips);
        AppCompatTextView tvSuitNumber = window.findViewById(R.id.tv_suit_number);
        AppCompatTextView tvSuitName = window.findViewById(R.id.tv_suit_name);
        AppCompatTextView tvSuitInfo = window.findViewById(R.id.tv_suit_info);
        AppCompatTextView tvSuitCoinNum = window.findViewById(R.id.tv_suit_coin_num);
        final AppCompatEditText etSuitNum = window.findViewById(R.id.et_suit_num);
        final AppCompatTextView tvSaleCoinsNum = window.findViewById(R.id.tv_sale_coins_num);
        final AppCompatTextView tvSaleMustMoney = window.findViewById(R.id.tv_sale_must_money);
        AppCompatTextView tvLetFree = window.findViewById(R.id.tv_let_free);
        AppCompatTextView tvCashPay = window.findViewById(R.id.tv_cash_pay);
        AppCompatTextView tvQrPay = window.findViewById(R.id.tv_qr_pay);
        final RadioGroup rgCoinOutType = window.findViewById(R.id.rg_coin_out_type);
        final AppCompatRadioButton rbEmtCoin = window.findViewById(R.id.rb_emt_coin);
        final AppCompatRadioButton rbTrueCoin = window.findViewById(R.id.rb_true_coin);

        final AppCompatTextView tvSuitCoinOutWayTitle = window.findViewById(R.id.tv_suit_coins_out_way_title);
        final RadioGroup rbCoinOutWay = window.findViewById(R.id.rg_coin_out_way);
        AppCompatRadioButton rbMachineOut = window.findViewById(R.id.rb_machine_coin_out);
        final AppCompatRadioButton rbPersonOut = window.findViewById(R.id.rb_person_coin_out);

        AppCompatImageView ivCardScan = window.findViewById(R.id.iv_card_scan);
        ivCardScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isReadNow) {
                    CardReadUtil.StartGetCardNum(getContext(), mReadCardTag, new CardReadEvent(new Bundle()));
                    isReadNow = true;
                }
            }
        });

        tvSuitNumber.setText(contentBean.getCode());
        tvSuitName.setText(contentBean.getName());
        tvSuitInfo.setText(contentBean.getDescription());
        tvSuitCoinNum.setText(String.valueOf(contentBean.getCoinNum()));

        if (contentBean.isIsMemberOnly()) {
            if (mSearchMenInfo != null && mSearchMenInfo.getMemberNo() != null) {
                tvCashPay.setClickable(true);
                tvQrPay.setClickable(true);
            } else {
                tvErrorTips.setText("该套餐仅限会员购买！");
                tvCashPay.setClickable(false);
                tvQrPay.setClickable(false);
            }
        }

        rgCoinOutType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == rbEmtCoin.getId()) {
                    mCoinOutType = "1";
                    tvSuitCoinOutWayTitle.setVisibility(View.GONE);
                    rbCoinOutWay.setVisibility(View.GONE);
                } else if (checkedId == rbTrueCoin.getId()) {
                    mCoinOutType = "0";
                    tvSuitCoinOutWayTitle.setVisibility(View.VISIBLE);
                    rbCoinOutWay.setVisibility(View.VISIBLE);
                }
            }
        });

        etSuitNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (StringUtil.isNotEmpty(etSuitNum.getText().toString())) {
                    mCurrentPrice = String.valueOf(StringUtil.IntegerValueOf(etSuitNum.getText().toString(), 0) * contentBean.getPrice());
                    tvSaleCoinsNum.setText(String.valueOf(StringUtil.IntegerValueOf(etSuitNum.getText().toString(), 0) * contentBean.getCoinNum()));
                    tvSaleMustMoney.setText("￥" + mCurrentPrice);
                } else {
                    tvSaleCoinsNum.setText("");
                    tvSaleMustMoney.setText("");
                }

                mCurrentTotalCoin = String.valueOf(StringUtil.IntegerValueOf(etSuitNum.getText().toString(), 0) * contentBean.getCoinNum());
            }
        });

        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (StringUtil.isNotEmpty(etPhone.getText().toString())) {
                    searchMemInfo(etPhone.getText().toString(), tvMemNum, tvCardUseTime, tvMemName);
                } else {
                    showLongToast(getString(R.string.suit_please_input_phone));
                }
            }
        });

        tvLetFree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLetFreeDialog();
            }
        });
        tvCashPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etIcCardNum.setFocusable(false);
                etPhone.setFocusable(false);
                etSuitNum.setFocusable(false);
                etIcCardNum.setFocusableInTouchMode(false);
                etPhone.setFocusableInTouchMode(false);
                etSuitNum.setFocusableInTouchMode(false);
                spAccount.setFocusable(false);
                spAccount.setFocusableInTouchMode(false);
                rgCoinOutType.setFocusable(false);
                rgCoinOutType.setFocusableInTouchMode(false);
                rbEmtCoin.setFocusable(false);
                rbEmtCoin.setFocusableInTouchMode(false);
                rbTrueCoin.setFocusable(false);
                rbTrueCoin.setFocusableInTouchMode(false);

                if (mCoinOutType.equals("1")) {
                    if (mSearchMenInfo != null && mSearchMenInfo.getMemberNo() != null) {
                        showCashPayDialog(contentBean, etSuitNum.getText().toString());
                    } else {
                        showLongToast("仅会员可购买电子币，请获取会员信息或者选择实体币");
                    }
                } else if (mCoinOutType.equals("2")) {
                    showCashPayDialog(contentBean, etSuitNum.getText().toString());
                } else {
                    showLongToast("请选择出币类型");
                }
            }
        });
        tvQrPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO 生成订单，成功后调用扫码器，开始扫码支付
                etIcCardNum.setFocusable(false);
                etPhone.setFocusable(false);
                etSuitNum.setFocusable(false);
                etIcCardNum.setFocusableInTouchMode(false);
                etPhone.setFocusableInTouchMode(false);
                etSuitNum.setFocusableInTouchMode(false);
                spAccount.setFocusable(false);
                spAccount.setFocusableInTouchMode(false);
                rgCoinOutType.setFocusable(false);
                rgCoinOutType.setFocusableInTouchMode(false);
                rbEmtCoin.setFocusable(false);
                rbEmtCoin.setFocusableInTouchMode(false);
                rbTrueCoin.setFocusable(false);
                rbTrueCoin.setFocusableInTouchMode(false);
                commitOrder(contentBean, etSuitNum.getText().toString(), "2", mCoinOutType);

                showPayStatusDialog(FustionTag.PAY_STATUS.WAIT_PAY);
            }
        });

//        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
//            @Override
//            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//                if (FusionCode.SCAN_TYPE.equals(FusionCode.QR_SCANNER)) {
//                    showShortToast("扫码成功");
//                    System.out.println("keycode=========>" + keyCode + "");
//                    char keyValue = (char) event.getUnicodeChar();
//                    // 生成二维码有大写字母的时候，会有空格出现，这个就是过滤空格的
//                    if (keyCode != END_CHAR_ID && keyCode != BLANK_CHAR_ID) {
//                        sb.append(keyValue);
//                    } else if (!TextUtils.isEmpty(sb.toString()) && keyCode != BLANK_CHAR_ID) {
//
//                        if (!FusionCode.QrIsLoading) {
//                            FusionCode.QrIsLoading = true;
//                            String qrCode = sb.toString().trim().replaceAll("\\s*", "");
//
//                            Bundle bundle = new Bundle();
//                            bundle.putString(FusionString.QR_CODE, qrCode);
//                            EventBus.getDefault().removeAllStickyEvents();
//                            EventBus.getDefault().postSticky(new QrScanEvent(bundle));
//
//                            sb.setLength(0);
//                        }
//                    }
//
//                    // 结束符去掉，不然有的界面不需要扫描功能，导致它扫描都内容叠加
//                    if (keyCode == END_CHAR_ID) {
//                        sb.setLength(0);
//                    }
//                }
//
//                return onKey(dialog, keyCode, event);
//            }
//        });
    }

    private void searchMemInfo(String phoneNum, final AppCompatTextView tvMemNum, AppCompatTextView tvCardUseTime, final AppCompatTextView tvMemName) {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("memberNo", "");
        params.put("memberPhone", phoneNum);
        HttpHelper.RestClientGet(params, HttpUrl.MEM_PHONE_SEARCH,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        Type type = new TypeToken<MemInfoEntity>() {
                        }.getType();
                        Gson gson = new Gson();
                        mSearchMenInfo = gson.fromJson(response, type);

                        tvMemNum.setText(mSearchMenInfo.getMemberNo());
                        tvMemName.setText(mSearchMenInfo.getMemberName());
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    private void commitOrder(SuitDetailEntity.ContentBean contentBean, String suitNum, final String payMethod, String coinOutType) {

        AuthorizeRecord authorizeRecord = new AuthorizeRecord();
        authorizeRecord.setAuthorizeId(1);

        mAuthorizeRecordList.add(authorizeRecord);
        /**
         * deptId：门店ID
         * businessDate：营业日期
         * shift：班次
         * code：套餐编号
         * comboNum：套餐数量
         * coinNum：游戏币数
         * receivableMoney：应收金额
         * actualMoney：实收金额
         * changeMoney：找零金额
         * payMethod：支付方式   1-现金 2-微信 3-支付宝 4-扫码核销
         * payStatus：支付状态
         * memberId：会员ID
         * memberNo：会员编号
         * coinOutType：出币类型 0-实物币 1-电子币
         * machineId：机台ID
         * machineCode：机台编号
         * remark：备注
         */
        JSONObject params = new JSONObject();
        params.put("deptId", FustionManager.mLoginData.getUser().getUser().getDept().getId());
        params.put("businessDate", FustionManager.mMachineData.getBusinessDate());
        params.put("shift", "1");
        params.put("code", contentBean.getCode());
        params.put("comboNum", suitNum);
        params.put("coinNum", String.valueOf(StringUtil.IntegerValueOf(suitNum, 0) * contentBean.getCoinNum()));
        params.put("receivableMoney", StringUtil.IntegerValueOf(suitNum, 0) * contentBean.getPrice());
        params.put("changeMoney", StringUtil.IntegerValueOf(suitNum, 0) * contentBean.getPrice());
        params.put("payMethod", payMethod);
        params.put("payStatus", "");
        if (mSearchMenInfo != null) {
            params.put("memberId", mSearchMenInfo.getId());
            params.put("memberNo", mSearchMenInfo.getMemberNo());
        }
        params.put("authorizeRecordList", JSON.toJSON(new ArrayList<>()));
        params.put("coinOutType", coinOutType);
        params.put("machineId", FustionManager.mMachineData.getMachineId());
        params.put("machineCode", FustionManager.mMachineData.getMachineCode());
        params.put("remark", "");

        mCurrentSuitName = contentBean.getName();

        HttpHelper.RestClientPostRaw(params, HttpUrl.COMBO_SUBMIT,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        if (code == 201) {
                            mCurrentBillNo = response;
                            if (payMethod.equals("1")) {
                                showPayStatusDialog(FustionTag.PAY_STATUS.PAY_SUCCESS);
                            } else if (payMethod.equals("2")) {
                                FusionCode.SCAN_TYPE = FusionCode.QR_SCANNER;
                            }
                        }
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

    }

    private void showCashPayDialog(final SuitDetailEntity.ContentBean contentBean, final String mSuitNum) {
        final Dialog dialog = new Dialog(getContext(), R.style.dialog);
        dialog.setCancelable(true);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_cash_pay);
        int width = (int) (DimenUtil.getScreenWidth() * 0.5);
        int height = (int) (DimenUtil.getScreenHeight() * 0.5);

        window.setLayout(width, height);

        AppCompatTextView tvSurePay = window.findViewById(R.id.tv_sure);
        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                commitOrder(contentBean, mSuitNum, "1", mCoinOutType);
            }
        });

    }

    private void showLetFreeDialog() {
        final Dialog dialog = new Dialog(getContext(), R.style.dialog);
        dialog.setCancelable(true);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_let_free);
        int width = (int) (DimenUtil.getScreenWidth() * 0.5);
        int height = (int) (DimenUtil.getScreenHeight() * 0.5);

        window.setLayout(width, height);
    }

    private void showCoinOutDialog(String wantNum) {
        final Dialog dialog = new Dialog(getContext(), R.style.dialog);
        dialog.setCancelable(true);
        dialog.show();
        Window window = dialog.getWindow();
        window.setContentView(R.layout.dialog_coin_out);
        int width = (int) (DimenUtil.getScreenWidth() * 0.5);
        int height = (int) (DimenUtil.getScreenHeight() * 0.5);

        AppCompatTextView tvTips = window.findViewById(R.id.tv_tips);
        AppCompatTextView tvWantNum = window.findViewById(R.id.tv_coin_want_num);
        tvCoinOutNum = window.findViewById(R.id.tv_coin_out_num);
        AppCompatTextView tvSure = window.findViewById(R.id.tv_sure);

        tvWantNum.setText(wantNum);

        tvTips.setText("出币完成");

        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        window.setLayout(width, height);
    }


    private void showPayStatusDialog(String status) {

        if (mPayStatusDialog == null) {
            mPayStatusDialog = new MyDialog(getContext(), R.style.dialog);
        }
        mPayStatusDialog.setCancelable(true);
        mPayStatusDialog.show();
        Window window = mPayStatusDialog.getWindow();
        window.setContentView(R.layout.dialog_pay_status);
        int width = (int) (DimenUtil.getScreenWidth() * 0.3);
        int height = (int) (DimenUtil.getScreenHeight() * 0.3);

        window.setLayout(width, height);

        AppCompatImageView ivPayStatusImg = window.findViewById(R.id.iv_status_img);
        AppCompatTextView tvPayStatusTip = window.findViewById(R.id.tv_pay_status_tips);
        AppCompatTextView tvWaitCoinOutTime = window.findViewById(R.id.tv_wait_coin_out_time);

        if (status.equals(FustionTag.PAY_STATUS.WAIT_PAY)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_pay_wait));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        } else if (status.equals(FustionTag.PAY_STATUS.PAYING)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_paying));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        } else if (status.equals(FustionTag.PAY_STATUS.PAY_SUCCESS)) {
            tvPayStatusTip.setText(getString(R.string.suit_pay_success));
            tvWaitCoinOutTime.setVisibility(View.VISIBLE);
            startCountDownTime(5, tvWaitCoinOutTime, mPayStatusDialog);
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
        } else if (status.equals(FustionTag.PAY_STATUS.PAY_FAILED)) {
            Glide.with(getContext()).load(R.mipmap.icon_logo).into(ivPayStatusImg);
            tvPayStatusTip.setText(getString(R.string.suit_pay_failed));
            tvWaitCoinOutTime.setVisibility(View.GONE);
        }

        mPayStatusDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                FusionCode.QrIsLoading = false;
                FusionCode.SCAN_TYPE = FusionCode.CANCEL;
            }
        });
    }

    @SuppressLint("HandlerLeak")
    final private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    break;
                case 2:
//                    textByteNum.setText("接收字节:" + byteNum);
//                    textBytes.setText(recvBytes.toString());
//                    recvBytes.setLength(0);
                    AtmosLogger.e(TAG, "状态：" + FustionManager.coinOutUtil.getStatus());
//                    textKey.setText("设置键：" + keyState);
                    break;
                case 3:
                    tvCoinOutNum.setText(String.valueOf(FustionManager.coinOutUtil.getCoinNum()));
                    AtmosLogger.e(TAG, "出币数：" + FustionManager.coinOutUtil.getCoinNum());
                    break;
                default:
                    break;
            }
        }
    };

    private void startCountDownTime(final long time, final AppCompatTextView tvWaitCoinOut, final Dialog dialog) {
        timer = new CountDownTimerUtil(time * 1000, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tvWaitCoinOut.setText(String.format(getString(R.string.suit_wait_start_coin_out), String.valueOf(millisUntilFinished / 1000)));
            }

            @Override
            public void onFinish() {
                dialog.dismiss();
                //TODO 开始出币
                FustionManager.coinOutUtil.setHandler(mHandler);
                FustionManager.coinOutUtil.SendCmd(2, 1);

                if (mPaySuitDetailDialog != null && mPaySuitDetailDialog.isShowing()) {
                    mPaySuitDetailDialog.dismiss();
                }

                showCoinOutDialog(mCurrentTotalCoin);


            }
        };
        timer.start();// 开始计时
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(CardReadEvent event) {
        if (event != null && event.getData() != null) {
            isReadNow = false;
            if (etIcCardNum != null) {
                etIcCardNum.setText((event.getData().getString("cardNum")).substring(2, 18));
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onQrScanEvent(QrScanEvent event) {
        if (event != null && event.getData() != null) {
            String qrCode = event.getData().getString(FusionString.QR_CODE);
            showShortToast(qrCode);
            qrPay(qrCode, mCurrentBillNo);

        }
    }

    private void qrPay(String qrCode, String billNo) {

        WeakHashMap<String, Object> params = new WeakHashMap<>();
        params.put("deptId", FustionManager.mLoginData.getUser().getUser().getDept().getId());
        params.put("authCode", qrCode);
        params.put("billNo", billNo);
        params.put("description", mCurrentSuitName);
        params.put("totalFee", "0.1");
        params.put("payBillType", "1");

        HttpHelper.RestClientPost(params, HttpUrl.CODE_PAY,
                new ISuccess() {
                    @Override
                    public void onSuccess(int code, String response) {
                        showShortToast("onSuccess:" + code + "||" + response);
                        FusionCode.QrIsLoading = false;
                        showPayStatusDialog(FustionTag.PAY_STATUS.PAY_SUCCESS);
                    }
                }, new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                }, new IFailure() {
                    @Override
                    public void onFailure() {

                    }
                });

        //TODO 开始调用支付接口，成功后出币

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        FusionCode.SCAN_TYPE = FusionCode.CANCEL;
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }
}
